package com.zgw.his.emr.parser;

import java.util.Iterator;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.zgw.his.emr.model.DetailRecord;
import com.zgw.his.emr.model.MedicalRecord;
import com.zgw.his.emr.model.PageRecord;
import com.zgw.his.emr.model.RootRecord;
import com.zgw.his.emr.model.TemplateRecord;
import com.zgw.his.emr.resource.TemplateSite;

/**
 * @author Z.G.W
 * */
public class XmlParser extends XmlSign {
	private String xmlContent;
	private MedicalRecord record;
	Document document;
	Element rootElement;

	public XmlParser(String content) {
		this.xmlContent = content;
	}

	//
	public MedicalRecord parser() throws DocumentException {
		document = DocumentHelper.parseText(xmlContent);
		rootElement = document.getRootElement();
		if (rootElement != null && rootElement.getName().equals(M_RECORD)) {
			record = createRoot(rootElement);
		}
		return record;
	}

	private RootRecord createRoot(Element re) {
		RootRecord record = new RootRecord();
		String id = rootElement.attributeValue(P_IDENTIFIER);
		String rt = rootElement.attributeValue(P_ROOT_TEMPLATE);
		record.setIdentifier(id);
		record.setRootTemlage(rt);

		// 生成页记录
		Iterator<Element> iterator = re.elementIterator(M_PAGE);
		while (iterator != null && iterator.hasNext()) {
			Element pe = iterator.next();
			PageRecord pr = createPage(pe);
			record.addChild(pr);
		}

		return record;
	}

	private PageRecord createPage(Element pe) {
		PageRecord record = new PageRecord();
		String pn = pe.attributeValue(P_PAGE_NUMBER);
		int pageNumber = Integer.parseInt(pn);
		record.setPageNumber(pageNumber);
		{
			TemplateRecord tr = new TemplateRecord();
			String tempId = pe.attributeValue(P_TEMPLATE_ID);
			tr.setIdentifier(tempId);
			tr.setTemplateUrl(TemplateSite.findUrl(tempId));
			Iterator<Element> iterator = pe.elementIterator(M_DETAIL);
			while (iterator != null && iterator.hasNext()) {
				DetailRecord dr = createDetail(iterator.next());
				if (dr != null)
					tr.addChild(dr);
			}
			record.setTemplate(tr);
		}
		return record;
	}

	private DetailRecord createDetail(Element de) {
		String code = de.attributeValue(P_CODE);
		if (code == null)
			return null;
		DetailRecord record = new DetailRecord(code);
		String text = de.getText();
		record.setText(text);
		return record;
	}
}
